package net.qiqbframework.messaging.annotation;


import net.qiqbframework.config.ConfigurationException;
import net.qiqbframework.messaging.InterceptorChain;
import net.qiqbframework.messaging.Message;
import net.qiqbframework.messaging.intercepting.MessageHandlerInterceptor;
import net.qiqbframework.messaging.intercepting.annotation.ResultHandler;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

/**
 * {@link ExecutableHandlerWrapper} that marks methods (meta-)annotated with {@link MessageHandlerInterceptor}
 * as interceptors. These methods need to be given special treatment when invoking handlers. Matching
 * interceptors need to be invoked first, allowing them to proceed the invocation chain.
 * <p>
 * This definition also recognizes interceptors only acting on the response. These must be meta-annotated with
 * {@link ResultHandler}.
 *
 */
public class MessageExecutableHandlerInterceptor implements ExecutableHandlerWrapper {

    @Override
    public @Nonnull MessageExecutableHandler wrap(@Nonnull MessageExecutableHandler original) {

        if (original.annotationAttributes(MessageHandlerInterceptor.class).isPresent()) {
            Optional<Map<String, Object>> attributes = original.annotationAttributes(ResultHandler.class);
            if (attributes.isPresent()) {
                return new ResultMessageExecutableHandler(original, (Class<?>) attributes.get().get("resultType"));
            }
            return new InterceptedMessageExecutableHandler(original);
        }
        return original;
    }

    private static class ResultMessageExecutableHandler extends WrappedMessageExecutableHandler implements InterceptingMember  {

        private final Class<?> expectedResultType;

        public ResultMessageExecutableHandler(MessageExecutableHandler original, Class<?> expectedResultType) {
            super(original);
            this.expectedResultType = expectedResultType;
            Method method = original.unwrap(Method.class).orElseThrow(() -> new ConfigurationException(
                    "Only methods can be marked as MessageHandlerInterceptor. Violating handler: " + original.signature()));
            boolean declaredInterceptorChain = Arrays.stream(method.getParameters())
                    .anyMatch(p -> p.getType().equals(InterceptorChain.class));
            if (declaredInterceptorChain) {
                throw new ConfigurationException("A MessageHandlerInterceptor acting on the invocation result must not declare a parameter of type InterceptorChain. Violating handler: " + original.signature());
            }
        }

        @Override
        public int priority() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean canHandle(@Nonnull Message<?> message) {
            return ResultParameterResolverFactory.ignoringResultParameters(() -> super.canHandle(message));
        }

        @Override
        public Object handle(@Nonnull Message<?> message, @Nullable Object target) throws Exception {
            InterceptorChain chain = InterceptorChainParameterResolverFactory.currentInterceptorChain();
            try {
                return chain.proceed();
            } catch (Exception e) {
                if (!expectedResultType.isInstance(e)) {
                    throw e;
                }
                return ResultParameterResolverFactory.callWithResult(e, () -> {
                    if (super.canHandle(message)) {
                        return super.handle(message, target);
                    }
                    throw e;
                });
            }
        }
    }

    private static class InterceptedMessageExecutableHandler extends WrappedMessageExecutableHandler implements InterceptingMember  {

        private final boolean shouldInvokeInterceptorChain;

        public InterceptedMessageExecutableHandler(MessageExecutableHandler original) {
            super(original);
            Method method = original.unwrap(Method.class).orElseThrow(() -> new ConfigurationException(
                    "Only methods can be marked as MessageHandlerInterceptor. Violating handler: " + original.signature()));
            shouldInvokeInterceptorChain = Arrays.stream(method.getParameters())
                    .noneMatch(p -> p.getType().equals(InterceptorChain.class));
            if (shouldInvokeInterceptorChain && !Void.TYPE.equals(method.getReturnType())) {
                throw new ConfigurationException("A MessageHandlerInterceptor must either return null or declare a parameter of type InterceptorChain. Violating handler: " + original.signature());
            }
        }

        @Override
        public Object handle(@Nonnull Message<?> message, @Nullable Object target) throws Exception {
            Object result = super.handle(message, target);
            if (shouldInvokeInterceptorChain) {
                return InterceptorChainParameterResolverFactory.currentInterceptorChain().proceed();
            }
            return result;
        }


    }
}
